import _ from 'lodash';
import moment from 'moment';
moment.locale('zh-cn');

export function initMoment(t) {
  if (!t) {
    return null;
  }
  if (Number.isInteger(t) && t < 10000000000) {
    t = moment.unix(t);
  } else {
    t = moment(t);
  }
  return t.isValid() ? t : null;
}

export function numFormat(num) {
  num = _.toNumber(num) || 0;
  if (num > 100000) {
    return '10w+';
  } else if (num >= 10000) {
    return _.round(num / 10000, 1) + 'w';
  } else if (num >= 1000) {
    return _.round(num / 1000, 1) + 'k';
  } else {
    return num;
  }
}

export function chineseNum(num) {
  if (num > 99999999) {
    return '超过一亿';
  }
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  let unit = ['', '十', '百', '千', '万'];
  num = parseInt(num);
  let getWan = (temp) => {
    let strArr = temp.toString().split('').reverse();
    let newNum = '';
    let newArr = [];
    strArr.forEach((item, index) => {
      newArr.unshift(
        item === '0' ? changeNum[item] : changeNum[item] + unit[index],
      );
    });
    let numArr = [];
    newArr.forEach((m, n) => {
      if (m !== '零') numArr.push(n);
    });
    if (newArr.length > 1) {
      newArr.forEach((m, n) => {
        if (newArr[newArr.length - 1] === '零') {
          if (n <= numArr[numArr.length - 1]) {
            newNum += m;
          }
        } else {
          newNum += m;
        }
      });
    } else {
      newNum = newArr[0];
    }

    return newNum.replace(/^一十/g, '十');
  };
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) {
    noWan = '0' + noWan;
  }
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
}

export async function sleep(t = 1000) {
  return new Promise((resolve) => {
    setTimeout(resolve, t);
  });
}

export function jsonParse(json) {
  try {
    return JSON.parse(json || null);
  } catch (e) {
    console.error('JSON ERROR', json);
    return null;
  }
}

export function downloadUrl(url, filename = '') {
  filename = filename || _.chain(url).split('/').last().value();
  return url + '?filename=' + filename;
}

export function circleNum(n) {
  n = parseInt(n);
  if (n > -1 && n < 51) {
    return '⓪①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿'[
      n
    ];
  }
  return '';
}

export function forTree(
  treeData,
  callback,
  children = 'children',
  parent = null,
) {
  _.forEach(treeData, (o) => {
    callback(o, parent);
    if (o[children] && o[children].length > 0) {
      forTree(o.children, callback, children, o);
    }
  });
}

export function findTree(treeData, iteratee, children = 'children') {
  let r = null;
  forTree(
    treeData,
    (o) => {
      if (_.attempt(_.iteratee(iteratee), o)) {
        r = o;
      }
    },
    children,
  );
  return r;
}

export function binaryResponse(err) {
  const data = _.get(err, 'response.data');
  if (_.isArrayBuffer(data)) {
    try {
      const td = new TextDecoder('utf-8');
      return Promise.resolve(JSON.parse(td.decode(data)));
    } catch (e) {}
  }
  return Promise.reject();
}

export function copyText(text) {
  const tag = document.createElement('input');
  tag.value = text;
  document.getElementsByTagName('body')[0].appendChild(tag);
  tag.select();
  document.execCommand('copy');
  tag.remove();
}

export function manualDownload(url, fileName) {
  const link = document.createElement('a');
  link.style.display = 'none';
  link.download = fileName;
  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
